import {
  FC,
  useEffect,
  useState,
  ReactElement,
  useCallback,
  useRef
} from 'react'
import {
  connect,
  EvaluationStateType,
  Loading,
  Dispatch,
  history,
  EvaluationType
} from 'umi'

import { Button, Modal, message } from 'antd'
import OrganizationPage from './components/check-organization'
import AddEvaluationPage from './components/add-evaluation'
import EditEvaluationPage from './components/edit-evaluation'
import CriteriaPage from './components/evaluation-criteria'
import WarningPage from './components/warning'
import { excelDownload } from '@/utils'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import styles from './index.less'
const { confirm } = Modal
let Status = {
  0: '禁用',
  1: '资料收集',
  2: '专家评审',
  3: '审核',
  4: '归档'
}
interface IProps {
  dispatch: Dispatch
  evaluationModel: EvaluationStateType
  evaluationLoding: Boolean
}
const Evaluation: FC<IProps> = ({
  dispatch,
  evaluationModel,
  evaluationLoding
}): ReactElement => {
  const { evaluationList } = evaluationModel

  const [showModal, setshowModal] = useState<boolean>(false)
  const [addshowModal, setAddshowModal] = useState<boolean>(false)
  const [editshowModal, setEditshowModal] = useState<boolean>(false)
  const [showCriteria, setShowCriteria] = useState<boolean>(false)
  const [warnshowModal, setWarnshowModal] = useState<boolean>(false)
  // 评价信息code
  const [code, setCode] = useState<string>('')
  const [criteriaCode, setCriteriaCode] = useState<string>('')
  const [record, setRecord] = useState<EvaluationType>({} as EvaluationType)
  const [dataSource, setDataSource] = useState<EvaluationType[]>([])
  const [status, setStatus] = useState<number>(0)
  const firstOnload = useRef<boolean>(true)

  // 查看机构
  const checkOrganization = useCallback((code: string) => {
    setCode(code)
    setshowModal(true)
  }, [])

  // 新增评价信息
  const addEvaluation = useCallback(() => {
    setAddshowModal(true)
  }, [])

  // 修改评价信息
  const editEvaluation = useCallback((record: EvaluationType) => {
    setRecord(record)
    setEditshowModal(true)
  }, [])

  // 查看评价指标
  const handleCriteria = useCallback((criteriaCode: string) => {
    setCriteriaCode(criteriaCode)
    setShowCriteria(true)
  }, [])

  // 处理预警信息
  const handleWarn = useCallback((code: string, status: number) => {
    setStatus(status)
    setCode(code)
    setWarnshowModal(true)
  }, [])

  // 获取评价信息列表
  const getEvaluationList = useCallback(() => {
    dispatch({
      type: 'evaluationModel/function_getBatchInfo',
      payload: {}
    })
  }, [])

  // 账号管理
  const handleAccount = useCallback((batchCode: string, status) => {
    history.replace({
      pathname: '/evaluation/account',
      query: {
        batchCode,
        status
      }
    })
  }, [])

  // 查看评价进度
  const handleProgress = (batchCode: string, status: number) => {
    history.replace({
      pathname: '/evaluation/progress',
      query: {
        batchCode,
        status: status + ''
      }
    })
  }

  const pointCheck = (batchCode: string, status: string) => {
    history.replace({
      pathname: '/evaluation/point-check',
      query: {
        batchCode,
        status
      }
    })
  }

  // 确认删除评价信息
  const handleDel = useCallback((code: string) => {
    confirm({
      title: '确认删除该评价信息?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        dispatch({
          type: 'evaluationModel/function_deleteBatchInfo',
          payload: {
            code
          },
          callback: (response) => {
            if (response.code === 200) {
              message.success('删除成功')
              getEvaluationList()
            }
          }
        })
      },
      onCancel() {
        console.log('Cancel')
      },
      okText: '确认',
      okType: 'danger',
      cancelText: '取消'
    })
  }, [])

  // 查看上传详情
  const UploadDetail = (code: string) => {
    history.replace({
      pathname: '/evaluation/upload-detail',
      query: {
        batchCode: code
      }
    })
  }

  const resultDownLoad = (
    name: string,
    batchCode: string,
    unitCode?: string
  ): void => {
    dispatch({
      type: 'evaluationModel/function_downloadReport',
      payload: {
        batchCode,
        unitCode
      },
      callback: (response) => {
        message.success('下载成功')
        const fileType = response.type.substring(
          response.type.lastIndexOf('/') + 1
        )
        excelDownload(response, `${name}评价打分结果.${fileType}`)
      }
    })
  }

  useEffect(() => {
    getEvaluationList()
  }, [])

  useEffect(() => {
    // 第一次加载不执行 避免调用2次
    if (firstOnload.current) {
      firstOnload.current = false
      return
    }
    // 解决异步导致数据丢失问题 数据单向流动，不要直接操作props数据
    const middle = JSON.parse(JSON.stringify(evaluationList))

    middle.forEach((item: EvaluationType, index: number) => {
      dispatch({
        type: 'evaluationModel/function_getBatchUnitInfo',
        payload: {
          code: item.code
        },
        callback: (response) => {
          item.unitNumber = response.obj.length
          dispatch({
            type: 'evaluationModel/function_getBatchWarningInfo',
            payload: {
              code: item.code
            },
            callback: (response) => {
              item.warnNumber = response.obj.length
              if (index == evaluationList.length - 1) {
                setDataSource(middle)
              }
            }
          })
        }
      })
    })
  }, [evaluationList])

  return (
    <>
      <div className={styles['home-wrapper']}>
        <div className={styles['add-btn']} onClick={addEvaluation}>
          新增评价信息
        </div>
        {dataSource?.map((item) => (
          <div className={styles['evaluation-item']} key={item.code}>
            <div className={styles['module-title']}>
              <span>项目预览</span>
              <span className={styles.year}>
                {new Date(item.createTime).getFullYear()}
              </span>
            </div>
            <div className={styles['module-content']}>
              <div className={styles['first-row']}>
                <span className={styles.name}>{item.name}</span>
                <span className={styles.content}>{item.content}</span>
              </div>
              <div className={styles['second-row']}>
                <div className={styles.unit}>
                  <span className={styles.label}>发起单位: </span>
                  <span>{item.unit}</span>
                </div>
                <div>
                  <span className={styles.label}>评价状态: </span>
                  <span>{Status[item.status]}</span>
                </div>
                <div>{/* <Switch defaultChecked /> */}</div>
              </div>

              <div className={styles['third-row']}>
                <div>
                  <span className={styles.label}>参与学段: </span>
                  <span>{item.grade}</span>
                </div>
                <div>
                  <span className={styles.label}>参与机构: </span>
                  <span>共{item.unitNumber}个机构</span>
                </div>
                <div>
                  <span
                    className={styles.detail}
                    onClick={() => checkOrganization(item.code)}
                  >
                    查看详情
                  </span>
                </div>
              </div>
              <div className={styles['fourth-row']}>
                <div>
                  <span className={styles.label}>创建时间: </span>
                  <span>{item.createTime}</span>
                </div>
                <div>
                  <span className={styles.label}>预警信息: </span>
                  <span className={styles['warning-info']}>
                    {item.warnNumber}
                    条预警
                  </span>
                </div>
                <div>
                  <span
                    className={styles.detail}
                    onClick={() => handleWarn(item.code, item.status)}
                  >
                    查看详情
                  </span>
                </div>
              </div>
              <div className={styles['fifth-row']}>
                <div>
                  <span className={styles.label}>评价指标: </span>
                  <span
                    onClick={() => handleCriteria(item.criteriaCode)}
                    className={styles.index}
                  >
                    {item.criteriaName}
                  </span>
                </div>
                <div></div>
                <div></div>
              </div>
              {item.status != 4 && item.status != 3 && item.status != 0 && (
                <div className={styles['sixth-row']}>
                  <div>
                    {item.status == 1 && (
                      <>
                        <span className={styles.label}>上传进度: </span>
                        <span
                          className={styles['check-progress']}
                          onClick={() => UploadDetail(item.code)}
                        >
                          点击查看
                        </span>
                      </>
                    )}

                    {item.status > 1 && (
                      <>
                        <span className={styles.label}>评审进度: </span>
                        <span
                          className={styles['check-progress']}
                          onClick={() => handleProgress(item.code, item.status)}
                        >
                          点击查看
                        </span>
                      </>
                    )}
                  </div>
                  {item.status > 1 && (
                    <div>
                      <span className={styles.label}>专家账号管理:</span>
                      <span
                        className={styles['account-entrance']}
                        onClick={() => handleAccount(item.code, item.status)}
                      >
                        入口&gt;&gt;&gt;
                      </span>
                    </div>
                  )}

                  <div>
                    <span className={styles.label}>分数审核: </span>
                    <span
                      className={styles['account-entrance']}
                      onClick={() => pointCheck(item.code, item.status + '')}
                    >
                      入口&gt;&gt;&gt;
                    </span>
                  </div>
                </div>
              )}
              {item.status == 3 && (
                <div className={styles['sixth-row']}>
                  <div>
                    <span className={styles.label}>分数审核: </span>
                    <span
                      className={styles['account-entrance']}
                      onClick={() => pointCheck(item.code, item.status + '')}
                    >
                      入口&gt;&gt;&gt;
                    </span>
                  </div>
                </div>
              )}

              {item.status == 4 && (
                <div>
                  <div>
                    <span className={styles.label}>评价结果: </span>
                    <span
                      onClick={() => resultDownLoad(item.name, item.code)}
                      className={styles['result-download']}
                    >
                      下载
                    </span>
                  </div>
                </div>
              )}
            </div>

            <div className={styles['operate-btn']}>
              <Button
                danger
                ghost
                onClick={() => handleDel(item.code)}
                disabled={item.status == 4}
              >
                删除
              </Button>
              <Button type="primary" onClick={() => editEvaluation(item)}>
                编辑
              </Button>
            </div>
          </div>
        ))}
      </div>

      {/* 参与机构 */}
      <OrganizationPage
        visible={showModal}
        code={code}
        hide={() => setshowModal(false)}
      />

      {/* 新建评价批次信息 */}
      <AddEvaluationPage
        visible={addshowModal}
        hide={() => setAddshowModal(false)}
        update={() => getEvaluationList()}
      />

      {/* 修改评价批次信息 */}
      <EditEvaluationPage
        record={record}
        visible={editshowModal}
        hide={() => setEditshowModal(false)}
        update={() => getEvaluationList()}
      />

      {/* 评价指标 */}
      <CriteriaPage
        visible={showCriteria}
        hide={() => setShowCriteria(false)}
        criteriaCode={criteriaCode}
      />

      {/* 评价预警 */}
      <WarningPage
        visible={warnshowModal}
        code={code}
        hide={() => setWarnshowModal(false)}
        update={() => getEvaluationList()}
        status={status}
      />
    </>
  )
}

const mapStateToProps = ({
  evaluationModel,
  loading
}: {
  evaluationModel: EvaluationStateType
  loading: Loading
}) => {
  return {
    evaluationModel,
    evaluationLoding: loading.models.evaluationModel
  }
}

export default connect(mapStateToProps)(Evaluation)
